#include"Heap.h"

void HeapInit(Heap* ph)
{
	assert(ph);
	ph->a = (HPDataType*)malloc(sizeof(HPDataType) * 4);
	if (ph->a == NULL)
	{
		perror("malloc fail!");
		return;
	}
	ph->size = 0;
	ph->capacity = 4;
}

void HeapInitArray(Heap* ph, int* array, int n)
{
	assert(ph);
	ph->a = (int*)malloc(sizeof(int) * n);
	if (ph->a == NULL)
	{
		perror("malloc fail!");
		return;
	}
	ph->size = n;
	ph->capacity = n;
	int i = 0;
	for (i = 0; i < n; i++)
	{
		HeapPush(ph->a, array[i]);
	}
}

void Swap(HPDataType* x, HPDataType* y)
{
	HPDataType tmp = *x;
	*x = *y;
	*y = tmp;
}

void HeapAdjustUp(HPDataType* a, int child)
{
	int parent = (child - 1) / 2;
	while (child > 0)
	{
		if (a[child] > a[parent])
		{
			Swap(&a[child], &a[parent]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}

void HeapPush(Heap* ph, HPDataType x)
{
	assert(ph);
	if (ph->size == ph->capacity)
	{
		HPDataType* tmp = (HPDataType*)realloc(ph->a, sizeof(HPDataType) * (ph->capacity) * 2);
		if (tmp == NULL)
		{
			perror("malloc fail!");
			return NULL;
		}
		ph->a = tmp;
		ph->capacity *= 2;
	}
	ph->a[ph->size++] = x;
	HeapAdjustUp(ph->a, ph->size - 1);
}

void HeapAdjustDown(HPDataType* a, int n, int parent)
{
	int child = parent * 2 + 1;
	while (child < n)
	{
		if (child + 1 < n && a[child + 1] < a[child])
		{
			child++;
		}
		if (a[parent] > a[child])
		{
			Swap(&a[child], &a[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
		{
			break;
		}
	}
}

bool isHeapEmpty(Heap* ph)
{
	assert(ph);
	return ph->size == 0;
}

void HeapPop(Heap* ph)
{
	assert(ph);
	assert(!isHeapEmpty(ph));
	swap(&ph->a[0], &ph->a[ph->size - 1]);
	ph->size--;
	HeapAdjustDown(ph->a, ph->size, 0);
}

void HeapTop(Heap* ph)
{
	assert(ph);
	return ph->a[0];
}

int HeapSize(Heap* ph)
{
	assert(ph);
	return ph->size;
}

void HeapDestroy(Heap* ph)
{
	assert(ph);
	free(ph->a);
	ph->a = NULL;
	ph->size = 0;
	ph->capacity = 0;
}